﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;

namespace Domzs.Web.Mvc.Captcha
{
    public class CaptchaImageHandler : IHttpHandler
    {
        // Methods
        public void ProcessRequest(HttpContext context)
        {
            string guid = context.Request.QueryString["guid"];
            CaptchaImage cachedCaptcha = CaptchaImage.GetCachedCaptcha(guid);
            if (string.IsNullOrEmpty(guid) || (cachedCaptcha == null))
            {
                context.Response.StatusCode = 0x194;
                context.Response.StatusDescription = "Not Found";
                context.Response.End();
            }
            else
            {
                using (Bitmap bitmap = cachedCaptcha.RenderImage())
                {
                    bitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
                }
                context.Response.ContentType = "image/gif";
                context.Response.StatusCode = 200;
                context.Response.StatusDescription = "OK";
                context.Response.End();
            }
        }

        // Properties
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}
